import React, { useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { ImageBackground, StyleSheet, Text, View, TouchableOpacity, TextInput, ToastAndroid } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage'
import { useAuth } from '../context/AuthProvider';
import axios from '../api/axios';
import { register } from '../api/user';
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: "center",
                alignItems: "center",
                ...style
            }
        }>
            <Text style={{ color: color ? color : '#FFF', fontSize: 18 }}>{children}</Text>
        </TouchableOpacity>
    )
}
const baseUrl = 'http://localhost:8080/';

const Login = ({ navigation }) => {
    const { user, setUser } = useAuth();
    const [username, setUsername] = useState("");
    const [pwd, setPwd] = useState("");
    const setUserId = async (value) => {
        try {
            await AsyncStorage.setItem('Key', value)
        } catch (e) {
            // saving error
        }
    }
    const toRegister = () => {
        navigation.navigate('register');
    }
    const login = () => {
        axios.post('/users/login', { username, pwd }).then(async res => {
            // console.log(res.msg);
            // console.log(res);
            // console.log(res.data);
            if (res.msg == "登陆成功") {
                ToastAndroid.show(res.msg, ToastAndroid.SHORT);
                // setUser(res.data[0]);
                setUser(res.data[0])
                navigation.navigate('head')
                AsyncStorage.setItem('user', JSON.stringify(res.data[0]), function (err) {
                    if (err) {
                        alert("aaaaa存储失败啦")
                    }
                })
                
            } else {
                ToastAndroid.show(res.msg, ToastAndroid.SHORT);
            }
        })
        // navigation.navigate('tab');
        // // console.log(username, pwd);
        // fetch(`${baseUrl}user/login`, {
        //     method: 'POST',
        //     mode: "cors",
        //     headers: {
        //         'Content-Type': 'application/json',
        //         "Connection": "close",
        //     },
        //     body: JSON.stringify({
        //         'userName': username,
        //         "password": pwd
        //     }),
        // }).then(res => res.json())
        //     .then(res => {
        //         console.log(res);
        //         if (res.code == "200") {
        //             ToastAndroid.show("登录成功", 3000);
        //             navigation.navigate('content');
        //             setUserId(res.data.userId);
        //             setUser(res.data);
        //         } else {
        //             ToastAndroid.show("登录失败", 3000);
        //         }
        //     })
    }
    return (
        <View style={styles.container}>
            <StatusBar style="auto" />
            <TextInput
                style={styles.input}
                placeholder="手机号/用户名"
                value={username}
                onChangeText={text => setUsername(text)}
            />
            <TextInput
                style={styles.input}
                placeholder="密码"
                value={pwd}
                onChangeText={text => setPwd(text)}
                secureTextEntry={true}
            />

            <Text
                onPress={toRegister}
                style={{
                    color: "#04543f",
                    marginLeft: 170,
                    marginBottom: 10
                }}>
                没有账户？点击注册
            </Text>

            <Btn
                style={{
                    backgroundColor: "#04543f",
                    width: 300,
                    height: 42,
                    borderRadius: 7,
                }}
                onPress={login}
            >
                登录
            </Btn>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        paddingTop: 150
    },
    input: {
        width: 300,
        height: 40,
        color: '#04543f',
        borderColor: '#D0EFE7',
        borderRadius: 7,
        borderWidth: 1,
        paddingLeft: 18,
        marginBottom: 20
    }
});

export default Login;
